import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/gestures.dart';

import '../../common/index.dart';
import '../index.dart';
import 'index.dart';

class SubscriptionPage extends GetView<SubscriptionController> {
  const SubscriptionPage({super.key});

  // 主视图
  Widget _buildView() {
    return Column(
      children: [
        SizedBox(height: 75.h),
        Expanded(
          child: Container(
            width: double.infinity,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [Color(0xFFFAE9FF), Color(0xFFFFF39A), Colors.white],
                stops: [0.0, 0.5, 0.8],
                tileMode: TileMode.clamp,
              ),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.r),
                topRight: Radius.circular(20.r),
              ),
            ),
            child: Column(
              children: [
                SizedBox(height: 10.h),
                SizedBox(
                  width: double.infinity,
                  height: 200.h,
                  child: Stack(
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 10.h,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            // 返回按钮
                            InkWell(
                              onTap: () {
                                HapticFeedback.selectionClick();
                                // 刷新Mine页面
                                if (Get.isRegistered<MineController>()) {
                                  Get.find<MineController>().load_user_data();
                                }
                                RouteUtil.pop();
                              },
                              child: Container(
                                width: 35.w,
                                height: 35.h,
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  gradient: LinearGradient(
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                    colors: [
                                      Color(0xFFFEED01),
                                      Color(0xFFB3A1FE),
                                    ],
                                  ),
                                ),
                                child: Center(
                                  child: Icon(
                                    Icons.close,
                                    color: Colors.black,
                                    size: 18.sp,
                                  ),
                                ),
                              ),
                            ),

                            // 恢复购买
                            TweenAnimationBuilder<double>(
                              tween: Tween<double>(begin: 1.0, end: 1.0),
                              duration: Duration(milliseconds: 200),
                              builder: (context, value, child) {
                                return Transform.scale(
                                  scale: value,
                                  child: child,
                                );
                              },
                              child: GestureDetector(
                                onTap: () {
                                  HapticFeedback.mediumImpact();
                                  controller.restore_purchases();
                                },
                                onTapDown: (_) {
                                  controller.restorePurchaseScale.value = 0.95;
                                },
                                onTapUp: (_) {
                                  controller.restorePurchaseScale.value = 1.0;
                                },
                                onTapCancel: () {
                                  controller.restorePurchaseScale.value = 1.0;
                                },
                                child: Obx(
                                  () => AnimatedScale(
                                    scale:
                                        controller.restorePurchaseScale.value,
                                    duration: Duration(milliseconds: 150),
                                    child: Text(
                                      'Restore Purchases',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 14.sp,
                                        fontWeight: FontWeight.w400,
                                        decoration: TextDecoration.underline,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      Center(
                        child: Text(
                          'Premium \nMembership',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: const Color(0xFFFCE74C),
                            fontSize: 40,
                            fontFamily: 'Arial Black',
                            fontWeight: FontWeight.w900,
                            height: 1.14,
                          ),
                        ),
                      ).paddingOnly(top: 45.h),

                      Center(
                        child: Container(
                          width: 182.w,
                          height: 182.h,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(AssetsImages.subBg),
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                      ).paddingOnly(top: 35.h),
                    ],
                  ),
                ),

                SizedBox(height: 35.h),
                _build_sub_conditions().paddingOnly(left: 40.w),

                SizedBox(height: 25.h),
                _buildSubscriptionList(),

                SizedBox(height: 20.h),
                Spacer(),

                _buildConfirmButton(),

                SizedBox(height: 15.h),
                _buildTermsText(),
                SizedBox(height: 70.h),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _build_sub_conditions() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: 18.w,
              height: 18.h,
              child: SvgPicture.asset(AssetsImages.subYes),
            ),
            SizedBox(width: 10.w),
            Text(
              'Premium verification badge',
              style: TextStyle(
                color: Colors.black,
                fontSize: 14.sp,
                fontWeight: FontWeight.w900,
              ),
            ),
          ],
        ),
        SizedBox(
          width: 229.w,
          height: 20.h,
          child: Text(
            'Shown in your profile to everyone\n',
            style: TextStyle(
              color: const Color(0xFFA4A4A4),
              fontSize: 10,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w600,
            ),
          ).paddingOnly(left: 30.w),
        ),
        SizedBox(height: 5.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: 18.w,
              height: 18.h,
              child: SvgPicture.asset(AssetsImages.subYes),
            ),
            SizedBox(width: 12.w),
            Text(
              'Unlimited Use of AI Plant Identification',
              style: TextStyle(
                color: Colors.black,
                fontSize: 14.sp,
                fontWeight: FontWeight.w900,
              ),
            ),
          ],
        ),
        SizedBox(height: 12.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: 18.w,
              height: 18.h,
              child: SvgPicture.asset(AssetsImages.subYes),
            ),
            SizedBox(width: 10.w),
            Text(
              'Unlimited Posting and Tracking of Plant Growth',
              style: TextStyle(
                color: Colors.black,
                fontSize: 14.sp,
                fontWeight: FontWeight.w900,
              ),
            ),
          ],
        ),
      ],
    );
  }

  // 构建订阅列表项
  Widget _buildSubscriptionList() {
    return Obx(
      () => Column(
        children: [
          // 周订阅
          _buildSubscriptionItem(
            price:
                '${controller.subscription_list[0]['price']}/${controller.subscription_list[0]['duration']}.',
            isSelected: controller.selectedPlan.value == 0,
            onTap: () => controller.selectPlan(0),
            index: 0,
          ),
          SizedBox(height: 10.h),

          // 月订阅
          _buildSubscriptionItem(
            price:
                '${controller.subscription_list[1]['price']}/${controller.subscription_list[1]['duration']}.',
            isSelected: controller.selectedPlan.value == 1,
            onTap: () => controller.selectPlan(1),
            index: 1,
          ),
          SizedBox(height: 10.h),

          // 季度订阅
          _buildSubscriptionItem(
            price:
                '${controller.subscription_list[2]['price']}/${controller.subscription_list[2]['duration']}.',
            isSelected: controller.selectedPlan.value == 2,
            onTap: () => controller.selectPlan(2),
            index: 2,
          ),
          SizedBox(height: 10.h),

          // 年度订阅
          _buildSubscriptionItem(
            price:
                '${controller.subscription_list[3]['price']}/${controller.subscription_list[3]['duration']}.',
            isSelected: controller.selectedPlan.value == 3,
            onTap: () => controller.selectPlan(3),
            index: 3,
          ),
        ],
      ),
    );
  }

  // 单个订阅项目
  Widget _buildSubscriptionItem({
    required String price,
    required bool isSelected,
    required VoidCallback onTap,
    required int index,
  }) {
    return AnimatedContainer(
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInOut,
      transform: Matrix4.identity()
        ..translate(isSelected ? 8.0 : 0.0, 0.0, 0.0),
      child: GestureDetector(
        onTap: () {
          HapticFeedback.selectionClick();
          onTap();
        },
        child: Container(
          width: 348.w,
          height: 57.61.h,
          decoration: ShapeDecoration(
            color: Colors.black,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10.r),
            ),
            shadows: isSelected
                ? [
                    BoxShadow(
                      color: Color(0xFFFEED01).withOpacity(0.3),
                      blurRadius: 10,
                      spreadRadius: 2,
                    ),
                  ]
                : null,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // 左侧文字部分
              Padding(
                padding: EdgeInsets.only(left: 20.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 订阅名称
                    SizedBox(
                      width: 81.22.w,
                      height: 18.h,
                      child: Text(
                        'Premium',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12.sp,
                          fontFamily: 'PingFang SC',
                          fontWeight: FontWeight.w400,
                          height: 1.50,
                          letterSpacing: 0.23,
                        ),
                      ),
                    ),
                    // 价格和时限
                    SizedBox(
                      width: 175.47.w,
                      height: 20.h,
                      child: Text(
                        price,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20.sp,
                          fontFamily: 'PingFang SC',
                          fontWeight: FontWeight.w600,
                          height: 0.90,
                          letterSpacing: 0.23,
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              // 右侧选择框
              Padding(
                padding: EdgeInsets.only(right: 20.w),
                child: AnimatedContainer(
                  duration: Duration(milliseconds: 300),
                  width: 24.w,
                  height: 24.h,
                  decoration: ShapeDecoration(
                    gradient: isSelected
                        ? LinearGradient(
                            begin: Alignment(0.50, -0.00),
                            end: Alignment(0.50, 1.00),
                            colors: [
                              const Color(0xFFFEED01),
                              const Color(0xFFB3A1FE),
                            ],
                          )
                        : null,
                    shape: OvalBorder(
                      side: isSelected
                          ? BorderSide.none
                          : BorderSide(width: 1, color: Colors.white),
                    ),
                  ),
                  child: isSelected
                      ? Center(
                          child: AnimatedOpacity(
                            opacity: isSelected ? 1.0 : 0.0,
                            duration: Duration(milliseconds: 200),
                            child: SvgPicture.asset(
                              AssetsImages.subYes,
                              width: 12.w,
                              height: 12.h,
                            ),
                          ),
                        )
                      : null,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建确认按钮
  Widget _buildConfirmButton() {
    return Obx(
      () => GestureDetector(
        onTap: () {
          HapticFeedback.mediumImpact();
          controller.purchaseSubscription();
        },
        onTapDown: (_) {
          controller.continueButtonScale.value = 0.95;
        },
        onTapUp: (_) {
          controller.continueButtonScale.value = 1.0;
        },
        onTapCancel: () {
          controller.continueButtonScale.value = 1.0;
        },
        child: AnimatedScale(
          scale: controller.continueButtonScale.value,
          duration: Duration(milliseconds: 150),
          child: Container(
            width: 348.w,
            height: 54.h,
            decoration: ShapeDecoration(
              gradient: LinearGradient(
                begin: Alignment(0.06, -0.00),
                end: Alignment(0.95, 1.00),
                colors: [const Color(0xFFFEED01), const Color(0xFFB3A1FE)],
              ),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(60.r),
              ),
              shadows: [
                BoxShadow(
                  color: Color(0xFFFEED01).withOpacity(0.3),
                  blurRadius: 15,
                  spreadRadius: 1,
                  offset: Offset(0, 5),
                ),
              ],
            ),
            child: Center(
              child: SizedBox(
                width: 69.w,
                height: 16.30.h,
                child: Text(
                  'Continue',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w600,
                    height: 1,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 构建条款文本
  Widget _buildTermsText() {
    return Text.rich(
      TextSpan(
        children: [
          TextSpan(
            text: 'By continuing, you agree to our',
            style: TextStyle(
              color: Colors.black.withOpacity(0.40),
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w400,
            ),
          ),
          TextSpan(
            text: ' ',
            style: TextStyle(
              color: Colors.black,
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w400,
            ),
          ),
          TextSpan(
            text: 'Terms of Service',
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                HapticFeedback.selectionClick();
                final Uri url = Uri.parse(
                  "https://www.freeprivacypolicy.com/live/3c2c565a-da96-4bda-9fd3-51e2625c89b5",
                );
                launchUrl(url, mode: LaunchMode.inAppWebView);
              },
            style: TextStyle(
              color: Colors.black,
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w400,
              decoration: TextDecoration.underline,
            ),
          ),
          TextSpan(
            text: ' ',
            style: TextStyle(
              color: Colors.black,
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w400,
            ),
          ),
          TextSpan(
            text: 'and',
            style: TextStyle(
              color: Colors.black.withOpacity(0.40),
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w400,
            ),
          ),
          TextSpan(
            text: ' ',
            style: TextStyle(
              color: Colors.black,
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w400,
            ),
          ),
          TextSpan(
            text: 'EULA',
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                HapticFeedback.selectionClick();
                final Uri url = Uri.parse(
                  "https://www.freeprivacypolicy.com/live/4c5a4a8b-f353-40b9-a2f5-1d407786f884",
                );
                launchUrl(url, mode: LaunchMode.inAppWebView);
              },
            style: TextStyle(
              color: Colors.black,
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w400,
              decoration: TextDecoration.underline,
            ),
          ),
        ],
      ),
      textAlign: TextAlign.center,
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SubscriptionController>(
      init: SubscriptionController(),
      id: "subscription",
      builder: (_) {
        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(AssetsImages.mineBg),
                fit: BoxFit.cover,
              ),
            ),
            child: _buildView(),
          ),
        );
      },
    );
  }
}
